import tools from '../utils/DateUtils'
import {ase} from '../utils/encryption'
import { ctx } from '../entrance/inter';

let time = tools.time;

export = class Cookie{
  //获取cookie
  public static get(ctx:ctx,key?:string){
    let cookie = this.pars(ctx);
    if(key===undefined)return cookie;
    return cookie[key];
  }

  public static set(ctx:ctx,name:any,value:any,obj:any={
    httpOnly:"httpOnly=httpOnly",
    path:"/",
  },data:any=[]){
    if(typeof name == 'string'){data.push({name,value,...obj})} else data=name;
    data.forEach((e,index)=>{
      let {name,value,httpOnly="httpOnly=httpOnly",path="/",time} = e;
      time?(this.expires_time(time)):(time=this.expires_time());
      (httpOnly==='none' || httpOnly==='') && (httpOnly='')
      data[index]=`${name}=${this.encryption(value)};${httpOnly};path=${path};expires=${time};`;
      data[index]=data[index].replace(/;;/g,";");
    })
    ctx.$res.setHeader('Set-Cookie',data);
  };

  //解析出请求头中的cookie
  public static pars(ctx:ctx,cookie={}){
    if(!ctx.$req.headers.cookie)return {};
    ctx.$req.headers.cookie.split(/ ;|; /g).filter(e=>e).forEach(e => {
      let a = e.split("=");
      // 解密
      let value = this.decryption(a[1]);
      
      cookie[a[0]]=value?value:a[1];  
    });
    return cookie;
  }


  //设置cook的时间
  public static expires_time(times=(time()+(1000*60*60*24))){
    return (new Date(times)).toUTCString();
  }

  //cookie加密
  public static encryption(str){
    if(str===undefined){new Error('加密内容为空')}
    return "cgem."+ase.encrypt(str);
  }

  //cookie解密
  public static decryption(str){
    if(!str)return undefined;
    //先判断是否为框架加密的cookie
    if(str.startsWith("cgem.")){
      str = str.substring(5)
    }else{return str}
    return ase.decrypt(str);
  }
}
